package com.xiaozhi.dialogue.tts.providers;

import com.xiaozhi.dialogue.tts.TtsService;
import com.xiaozhi.entity.SysConfig;
import com.xiaozhi.utils.AudioUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.UUID;

public class SiliconflowTtsService implements TtsService {
    private static final Logger logger = LoggerFactory.getLogger(SiliconflowTtsService.class);

    private static final String PROVIDER_NAME = "siliconflow";
    private static final String BASE_URL = "https://api.siliconflow.cn/v1/audio/speech";
    
    private SysConfig config;
    private String voiceName;
    private String outputPath;

    public SiliconflowTtsService(SysConfig config, String voiceName, String outputPath) {
        this.config = config;
        this.voiceName = voiceName;
        this.outputPath = outputPath;
    }

    @Override
    public String getProviderName() {
        return PROVIDER_NAME;
    }

    @Override
    public String audioFormat() {
        return "mp3";
    }

    @Override
    public String textToSpeech(String text) throws Exception {

        // 验证输入文本
        if (text == null || text.trim().isEmpty()) {
            logger.warn("输入文本为空，无法生成语音");
            return null;
        }
        // 获取API密钥
        String apiKey = config.getApiKey();
        if (apiKey == null || apiKey.isEmpty()) {
            throw new IllegalArgumentException("Missing API key for Siliconflow TTS service");
        }

        // 创建请求JSON
        String requestBody = String.format(
            "{\"model\":\"%s\",\"input\":\"%s\",\"voice\":\"%s\"}",
            "FunAudioLLM/CosyVoice2-0.5B",
            text.replace("\"", "\\\""), // 转义双引号
                "FunAudioLLM/CosyVoice2-0.5B:alex"
        );

        // 发送HTTP POST请求
        byte[] audioData = sendTtsRequest(apiKey, requestBody);

        if (audioData == null || audioData.length == 0) {
            logger.warn("TTS服务返回空音频数据，文本: {}", text);
            return null;
        }
        
        // 保存MP3文件
        String fileName = UUID.randomUUID().toString().replace("-", "") + ".mp3";
        String fullPath = outputPath + fileName;
        
        try (FileOutputStream fos = new FileOutputStream(fullPath)) {
            fos.write(audioData);
        }

        logger.debug("MP3文件保存成功: {}", fullPath);
        // 1. 将MP3转换为PCM (已经设置为16kHz采样率和单声道)
        byte[] pcmData = AudioUtils.mp3ToPcm(fullPath);
        if (pcmData == null || pcmData.length == 0) {
            logger.warn("MP3转PCM失败，文件: {}", fullPath);
            return null;
        }
        logger.debug("MP3转PCM成功，PCM数据大小: {} 字节", pcmData.length);
        // 2. 将PCM转换回WAV (使用AudioUtils中的设置：16kHz, 单声道, 160kbps)
        String resampledFileName = AudioUtils.saveAsWav(pcmData);
        if (resampledFileName == null || resampledFileName.isEmpty()) {
            logger.warn("保存WAV文件失败");
            return null;
        }
        logger.debug("WAV文件保存成功: {}", resampledFileName);
        // 3. 删除原始文件
        Files.deleteIfExists(Paths.get(fullPath));

        // 4. 返回重采样后的文件路径
        return AudioUtils.AUDIO_PATH + resampledFileName;
    }

    private byte[] sendTtsRequest(String apiKey, String requestBody) throws Exception {
        URL url = new URL(BASE_URL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        
        // 设置请求头
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Authorization", "Bearer " + apiKey);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "audio/mpeg");
        connection.setDoOutput(true);
        
        // 发送请求体
        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = requestBody.getBytes("utf-8");
            os.write(input, 0, input.length);
        }
        
        // 检查响应码
        int responseCode = connection.getResponseCode();
        if (responseCode != HttpURLConnection.HTTP_OK) {
            String errorMsg = readErrorResponse(connection);

            System.out.println("Siliconflow TTS 接口错误信息 error: " + responseCode + " - " + errorMsg);
            throw new RuntimeException("Siliconflow TTS API error: " + responseCode + " - " + errorMsg);
        }
        
        // 读取音频数据
        try (InputStream is = connection.getInputStream()) {
            return is.readAllBytes();
        }
    }
    
    private String readErrorResponse(HttpURLConnection connection) {
        try (InputStream is = connection.getErrorStream()) {
            if (is != null) {
                return new String(is.readAllBytes(), "utf-8");
            }
        } catch (Exception e) {
            logger.warn("Failed to read error response", e);
        }
        return "Unknown error";
    }
}